layui.use(["element", "table", "form", "laydate", "okMock", "jquery","util", "api","layer"], function () {
    let table = layui.table;
    let laydate = layui.laydate;
    let layer = layui.layer;
    let okMock = layui.okMock;
    let util = layui.util;
    let $ = layui.jquery;
    let api = layui.api;
    okLoading.close();
    laydate.render({elem: "#startTime", type: "datetime"});
    laydate.render({elem: "#endTime", type: "datetime"});

    var USER_STATUS_START = '0';
    var USER_STATUS_STOP = '1';

    // $.ajaxSetup({
    // 	beforeSend:function () {
    //
    //    },
    //    complete: function (xhr, status) {
    //        if (xhr.status == 200)
    //            console.log("----")
    //    }
    // })

    let userTable = table.render({
        elem: "#tableId",
        url: okMock.api.user.list,
        limit: 10,
        page: true,
        toolbar: "#toolbarTpl",
        size: "sm",
        headers:{token: getToken()},
        parseData: function (res) {
            return {
                code: res.code,
                msg: res.name,
                //count: res.code == RESP_SUCCESS ? res.extend.page.totalCounts : 0,
                count: res.extend.page.totalCounts,
                //data: res.code == RESP_SUCCESS ? res.extend.page.data.list : ''
                data: res.extend.page.data.list
            };
        },
        request: {
            pageName:'currentPage',
            limitName:'pageCounts'
        },
        response: {
            statusCode: "100"
        },
        beforeSuccessDone: function (res, curr) {
            //console.log(res);
            if(res.code !== api.responseCode.success) {
                api.defaultErrorhandler(res)
                return false;
            }
        },
        cols: [[
            {type: "checkbox", width: 50},
            {type: "numbers", title:'序号',width: 50},
            {field: "userId", title: "用户ID", width: 100, sort: true},
            {field: "username", title: "用户账号", width: 100},
            {field: "nickname", title: "用户昵称", width: 120},
            {field: "userType", title: "账户类型", width: 100, align: "center", templet: "#userTypeTpl"},
            {field: "deptName", title: "所在部门", width: 100, align: "center"},
            {field: "sysPost", title: "职位", width: 80, align: 'center',
                templet: function (d) {
                    if(d.sysPost != null) {
                        return d.sysPost.postName;
                    }
                    return '-';
                }
            },
            {field: "mobile", title: "手机号码", width: 120},
            {field: "email", title: "邮件账号", width: 260},
            {field: "userStatus", title: "用户状态", width: 100, align: "center",
                templet: function (d) {
                    const d_status = d.userStatus;
                    if(d_status == '0') {
                        return '<span class="layui-badge layui-bg-green">启用</span>'
                    }else if(d_status == '1') {
                        return '<span class="layui-badge">停用</span>'
                    }
                }
            },
            //{field: "appid", title: "APPID", width: 130,align: "center"},
            //{field: "openid", title: "OPENID", width: 130,align: "center"},
            {field: "loginIp", title: "上回登录IP", width: 120,align: "center", hide: true},
            {field: "loginDate", title: "上回登录时间", width: 180,align: "center", hide: true},
            {field: "createBy", title: "创建人员", width: 120,align: "center", hide: true,
                templet: function (d) {
                    if(d.createBy == null || d.createBy == '') {
                        return '-'
                    }
                    return d.createBy
                }
            },
            {field: "createAt", title: "创建时间", width: 180,align: "center", hide: true,
                templet: function(d){
                    var d_createAt = d.createAt
                    if(d_createAt == null){
                        return '-'
                    }
                    return util.toDateString(d_createAt, 'yyyy-MM-dd HH:mm:ss')
                }
            },
            {field: "updateBy", title: "修改人员", width: 120,align: "center", hide: true,
                templet: function (d) {
                    if(d.updateBy == null || d.updateBy == '') {
                        return '-'
                    }
                    return d.updateBy
                }
            },
            {field: "updateAt", title: "修改时间", width: 180,align: "center", hide: true,
                templet: function(d){
                    var d_updateAt = d.updateAt
                    if(d_updateAt == null){
                        return '-'
                    }
                    return util.toDateString(d_updateAt, 'yyyy-MM-dd HH:mm:ss')
                }
            },
            {field: "remark", title: "备注", width: 200, hide: true},
            {title: "操作", width: 160, align: "center", fixed: 'right',  templet: "#operationTpl"}
        ]],
        done: function (res, curr, count) {// 服务器返回数据, 当前页码, 总记录数
            //console.log(res, curr, count);
            //console.log("sysuser.html " + res.code);
            //$('.layui-table-tool-self').addClass('layui-hide')// 表右上角工具栏 父DIV class
            //$('.layui-table-tool-self').find('div')  //每一个div工具

            api.doShowUserPermsMenus();
        }
    });

    // form.on("submit(search)", function (data) {
    //    userTable.reload({
    // 		where: data.field,
    // 		url:'',//
    // 		page: {curr: 1}
    // 	});
    // 	console.log("0000")
    // 	return false;
    // });

    table.on("toolbar(tableFilter)", function (obj) {
        switch (obj.event) {
            case "add":
                add();
                break;
            case "batchDel":
                batchDel();
                break;
        }
    });

    table.on("tool(tableFilter)", function (obj) {
        let data = obj.data;
        switch (obj.event) {
            case "modify":
                edit(data.userId, data);
                break;
            case "delete":
                del(data.userId, data);
                break;
            case "role":
                perms(data);
                break;
            case "pswproxy":
                pswproxy(data);
                break;
            case "userstat":
                userstat(data, obj);
                break;
        }
    });

    function add() {
        api.open("添加菜单", "sysuser-add.html", "90%", "90%",
            function (layero, index) {
                var body = layer.getChildFrame('body', index);
                var iframeWin = window[layero.find('iframe')[0]['name']]; //得到iframe页的窗口对象，执行iframe页的方法：iframeWin.method();

                var elePost = body.find("#postId");
                elePost.append('<option value="">工作岗位</option>')
                $.ajax({
                    url:okMock.api.post.selectBoxList,
                    success: function (res, status) {
                        if(res.code == api.responseCode.success) {
                            $.each(res.extend.data, function (idx, obj) {
                                elePost.append('<option value="'+ obj.postId +'">'+ obj.postName + '/ ' + obj.postCode +'</option>');
                            })
                        }
                    },
                    complete: function () {
                        //iframeWin.form.render('select','sysuser-add');
                        iframeWin.iframeRenderForm();
                    }
                });

            }, function () {
                userTable.reload();
            })
    }

    function batchDel() {
        api.confirm("确定要批量删除吗？", function (index) {
            layer.close(index);
            var checkStatusData = table.checkStatus('tableId').data;
            var ids = [];
            if(checkStatusData.length > 0 ) {
                $.each(checkStatusData, function (idx, obj) {
                    ids.push(obj.userId)
                })
            }else{
                api.yellowQuestionMsg("未选择有效数据");
                return;
            }
            //console.log(ids)
            if (ids.length > 0) {
                deleteByIds(ids)
            }
        });
    }

    function edit(id, data) {
        api.open("修改用户", "sysuser-edit.html?id=" + id, "90%", "90%",
            function (layero, index){
                //回显数据
                var body = layer.getChildFrame('body', index);//获取弹出层的dom元素
                body.find("#userId").val(data.userId);
                body.find("#username").val(data.username);
                body.find("#mobile").val(data.mobile);
                body.find("#email").val(data.email);
                body.find("#nickname").val(data.nickname);
                body.find("input[name='remark']").val(data.remark);
                // 类型 radio 赋值
                var eleType = body.find("input[name='userType'][value='"+ data.userType +"']");
                $(eleType).attr('checked', true);
                // 部门数据
                body.find('#deptId').val(data.deptId);
                body.find('#deptName').val(data.deptName);

                //职位回显
                var iframeWin = window[layero.find('iframe')[0]['name']]; //得到iframe页的窗口对象，执行iframe页的方法：iframeWin.method();

                var elePost = body.find("#postId");
                elePost.append('<option value="">工作岗位</option>')
                $.ajax({
                    url:okMock.api.post.selectBoxList,
                    success: function (res, status) {
                        if(res.code == api.responseCode.success) {
                            $.each(res.extend.data, function (idx, obj) {
                                if(data.sysPost != null) {
                                    if(obj.postId == data.sysPost.postId) {
                                        elePost.append('<option value="'+ obj.postId +'" selected>'+ obj.postName + '/ ' + obj.postCode +'</option>');
                                    } else {
                                        elePost.append('<option value="'+ obj.postId +'">'+ obj.postName + '/ ' + obj.postCode +'</option>');
                                    }
                                } else {
                                    elePost.append('<option value="'+ obj.postId +'">'+ obj.postName + '/ ' + obj.postCode +'</option>');
                                }
                            })
                        }
                    },
                    complete: function () {
                        iframeWin.iframeRenderForm();
                    }
                });

            },
            function () {
                userTable.reload();
            }
        )
    }

    void function () {
    }();



    function del(id, data) {
        api.confirm("确定要删除【 "+ data.username +" 】用户吗？", function () {
            var ids = [];
            ids.push(data.userId);
            deleteByIds(ids);
        })
    }

    function perms(param) {
        api.open("修改用户", "sysuser-roles.html", "90%", "90%",
            function (layero, index) {
                //回显数据
                var body = layer.getChildFrame('body', index);//获取弹出层的dom元素
                body.find('#userId').val(param.userId);
                body.find('#username').val(param.username);
            });
    }

    function pswproxy(data) {
        api.confirm("确定要给【 "+ data.username +" 】初始化密码吗？", function (index) {
            layer.close(index);
            api.request({
                url: okMock.api.user.initializePassword,
                where: {userId: data.userId}
            },function (res, stat) {
                api.greenLaughMsg("成功初始化密码。")
            });
        });
    }

    function userstat(data, obj) {
        if(data.userStatus === USER_STATUS_START) {//停用
            api.confirm("是否停用【 "+ data.username +" 】账号？", function (index) {
                layer.close(index);
                api.request({
                    url: okMock.api.user.updateUserStatus,
                    where: {userId: data.userId}
                },function (res, stat) {
                    obj.update({
                        userStatus: USER_STATUS_STOP
                    });
                });
            });
        } else if(data.userStatus === USER_STATUS_STOP) {//启用
            api.confirm("是否启用【 "+ data.username +" 】账号？", function (index) {
                layer.close(index);
                api.request({
                    url: okMock.api.user.updateUserStatus,
                    where: {userId: data.userId}
                },function (res, stat) {
                    obj.update({
                        userStatus: USER_STATUS_START
                    });
                });
            });
        }
    }

    function deleteByIds(ids) {
        api.request({
            url: okMock.api.user.deleteByIds,
            where:{ids: ids},
            traditional: true
        },function (res, stat) {
            api.tableSuccessMsg(res.name);
        },function () {
            userTable.reload();
        })
    }
})